<!--
 * @Descripttion: 访客管理
 * @version:
 * @Author: wl
 * @Date: 2020-05-21 17:00:50
 * @LastEditors: wl
 * @LastEditTime: 2020-08-06 17:44:53
-->
<template>
  <div>
    <page :asideShow="asideShow">
      <div slot="toolbar">
        <el-form :inline="true" :model="filters" label-width="90px" label-position="right">
          <el-form-item label="姓名：">
            <el-input placeholder="请输入" clearable v-model="filters.name"></el-input>
          </el-form-item>
          <el-form-item label="选择小区:">
            <el-select v-model="filters.CID" filterable placeholder="请选择" clearable @change="refreshPageRequest(1)">
              <el-option v-for="item in villageList" :key="item.CID" :label="item.name" :value="item.CID"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="性别：">
            <el-select @change="refreshPageRequest(1)" v-model="filters.gender" placeholder="请选择" clearable>
              <el-option v-for="item in optionsSex" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人员来源：">
            <el-select v-model="filters.registration" @change="refreshPageRequest(1)" placeholder="请选择" clearable>
              <el-option v-for="item in registOption" :key="item.DID" :label="item.name" :value="item.DID"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button type="primary" @click="handleQuery('a')">查询</el-button>
      </div>
      <div slot="content">
        <el-table :header-cell-style="{ background: '#e7eaf0', color: '#606266' }" v-loading="loading"
          element-loading-text="加载中..." :data="visitantList" style="width: 100%; margin-bottom: 20px">
          <el-table-column prop="name" header-align="center" align="center" label="姓名">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" align="center" width="100">
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.gender == 1">女</span>
                <span v-else>男</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="idCard" label="身份证" width="180" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.idCard }}
              </span>
              <span v-else>{{ hideOfString(scope.row.idCard) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="year" label="年龄" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.year > 1890">
                {{
                    new Date().getFullYear() - scope.row.year > 0
                      ? new Date().getFullYear() - scope.row.year
                      : '不详'
                }}
              </div>
              <div v-else>不详</div>
            </template>
          </el-table-column>
          <el-table-column width="150" prop="CIDD" label="所在小区" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.CIDD ? scope.row.CIDD : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="150" prop="registration" label="人员来源" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.regist }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="访问地址" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.address ? scope.row.address : '—' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="提交时间" align="center">
            <template slot-scope="scope">
              <span>{{ $format(scope.row.insertTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="280"
            :label="$t('action.operation')">
            <template slot-scope="scope">
              <!-- <el-button
                size="mini"
                type="primary"
                @click="handleEditImg(scope.row)"
                v-show="hasPerm('personnel:visitor:details')"
              >查看头像</el-button>-->
              <el-button size="mini" type="warning" @click="
                getCheckEncryption() ? get_sensitive_fields(scope.row, checkPhoto) : (isCheckEncryption = true)
              " v-show="hasPerm('personnel:visitor:show')">
                查看
              </el-button>
              <el-button size="mini" type="success"
                @click="getCheckEncryption() ? getFamily(scope.row) : (isCheckEncryption = true)"
                v-show="hasPerm('personnel:onehousehold:detail')">
                详情
              </el-button>
              <el-button size="mini" type="success"
                @click="getCheckEncryption() ? gettime(scope.row) : (isCheckEncryption = true)"
                v-show="hasPerm('personnel:onehousehold:detail')">
                访问记录
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 头像 -->
        <!-- 弹框 -->
        <el-dialog :visible.sync="dialogVisibleImg" :before-close="handleClose" width="30%">
          <img style="width: 100%" :src="getItemPhoto(currentImg)" class="imgDia" v-image-preview />
        </el-dialog>
        <el-dialog class="dialog-container" title="访问记录" :visible.sync="editVisible" :modal-append-to-body="false">
          <!-- <div>
            <el-divider>基本信息</el-divider>
            <div style="display: flex; justify-content: space-between">
              <div class="mt20">访问时间：{{ accesstime ? accesstime : '-' }}</div>
              <div class="mt20">离开时间：{{ outtime ? outtime : '-' }}</div>
              <div class="mt20">进入地点：{{ names ? names : '-' }}</div>
            </div>
          </div> -->
          <el-date-picker v-model="selectTime" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" @change="timeChange">
          </el-date-picker>
          <el-table :header-cell-style="{ background: '#e7eaf0', color: '#606266' }" v-loading="passLoading"
            element-loading-text="加载中..." :data="timeArr" style="width: 100%; margin-top: 20px">
            <el-table-column prop="name" label="姓名" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.info.persionName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="小区" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.CName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="设备" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.device.Name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="时间" align="center">
              <template slot-scope="scope">
                <span>{{ $format(scope.row.time) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>
        <el-dialog title="被访家庭详情" :visible.sync="dialogTableVisible" :before-close="handleClose1">
          <div>
            <el-table border stripe style="width: 100%" v-loading="loading" element-loading-text="加载中..."
              :data="familyArr">
              <el-table-column label="头像" width="100px" header-align="center" align="center">
                <template slot-scope="scope">
                  <img v-if="scope.row.person && scope.row.person[0] && scope.row.person[0].photo"
                    :src="baseUrlImage + 'avatar/' + scope.row.person[0].photo" alt style="width: 50px; height: 50px"
                    v-image-preview />
                </template>
              </el-table-column>
              <el-table-column label="姓名" width="180" header-align="center" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.person && scope.row.person[0] && scope.row.person[0].name">
                    {{ scope.row.person[0].name }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column header-align="center" align="center" label="性别">
                <template slot-scope="scope">
                  <span v-if="scope.row.person && scope.row.person[0] && scope.row.person[0].gender == 0">男</span>
                  <span v-if="scope.row.person && scope.row.person[0] && scope.row.person[0].gender == 1">女</span>
                </template>
              </el-table-column>
              <el-table-column prop="year" label="年龄" align="center">
                <template slot-scope="scope">
                  <div v-if="scope.row.person && scope.row.person[0] && scope.row.person[0].year > 1890">
                    {{
                        new Date().getFullYear() - scope.row.person[0].year > 0
                          ? new Date().getFullYear() - scope.row.person[0].year
                          : '不详'
                    }}
                  </div>
                  <div v-else>不详</div>
                </template>
              </el-table-column>
              <el-table-column label="证件号码" width="180" header-align="center" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.person && scope.row.person[0] && scope.row.person[0].idCard">
                    {{ scope.row.person[0].idCard }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="联系方式" width="180" header-align="center" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.person && scope.row.person[0] && scope.row.person[0].phone">
                    {{ scope.row.person[0].phone }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-dialog>
      </div>
      <div slot="footer">
        <el-pagination layout="total, prev, pager, next, jumper" @current-change="refreshPageRequest"
          :current-page="pageRequest.page" :page-size="pageRequest.pageSize" :total="totalSize"
          style="float: right"></el-pagination>
      </div>
    </page>
    <el-dialog title="身份验证" :visible.sync="isCheckEncryption">
      <CheckEncryption @close="isCheckEncryption = false"></CheckEncryption>
    </el-dialog>
  </div>
</template>

<script>
import CheckEncryption from '@/components/CheckEncryption';
export default {
  components: {
    CheckEncryption
  },
  data() {
    return {
      isCheckEncryption: false,
      baseUrlImage: this.global.baseUrlImage,
      currentImg: '',
      selectTime: [],
      passLoading: false,
      // 头像弹框
      dialogVisibleImg: false,
      asideShow: false,
      filters: {
        corpId: 0,

        name: '',
        insertTime: '',
        updateTime: ''
      },
      pageRequest: {
        page: 1,
        pageSize: 10
      },
      loading: false,
      timeArr: [],
      totalSize: 0,
      // 访客列表
      visitantList: [],
      editVisible: false,
      dialogTableVisible: false,
      dialogTable: false,
      // 人员类型
      houseList: [],
      dictList: {},
      photoCheck: 0,
      dataForm: {},
      familyArr: [],
      HID: '',
      accesstime: '',
      outtime: '',
      names: '',
      villageList: [],
      optionsSex: [
        {
          value: 0,
          label: '男'
        },
        {
          value: 1,
          label: '女'
        }
      ],
      registOption: [],
      passFilter: {}
    };
  },
  mounted() {
    this.dictList = JSON.parse(sessionStorage.getItem('dictData'));
    this.handleQuery();
    this.getCommunityList();
    this.getDirList();
  },
  methods: {
    // 获取来源
    getDirList() {
      //调用字典
      this.dictList = JSON.parse(sessionStorage.getItem('dictData'));
      this.registOption = this.dictList.sys_persion_source;
      this.registOption.map((item) => {
        item.value = item.DID;
        item.name = item.name;
      });
    },
    gettime(row) {
      this.editVisible = true;
      this.handltime(row);
    },
    // 家庭成员
    getFamily(row) {
      this.dialogTableVisible = true;
      this.parentHandleclick(row.houser);
    },
    //关闭弹窗
    handleClose1() {
      this.dialogTableVisible = false;
    },
    //关闭弹窗
    handleClose2() {
      this.dialogTable = false;
    },
    //查看
    checkPhoto(row) {
      if (row.photoCheck == this.photoCheck) {
        this.photoCheck = 0;
      } else {
        this.$nextTick(() => {
          //nextTick并不是用来监听DOM变更，它的作用是一次性更改数据，并且渲染DOM
          this.$set(this.visitantList, this.photoCheck - 1, row);
        });
        this.photoCheck = row.photoCheck;
      }
    },
    // 拼接图片
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + 'avatar/' + id;
      return url;
    },
    handleClose() {
      this.dialogVisibleImg = false;
    },
    // 查看头像
    handleEditImg: function (params) {
      if (params.photo) {
        this.currentImg = params.photo;
      }
      this.dialogVisibleImg = true;
    },

    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = '';
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 上传图片
    async upLoad(param) {
      var imgup = '';
      await this.getBase64(param.file).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup
      };
      this.$api.imgAdd
        .addimgPer(paramd)
        .then((res) => {
          this.imgURL = res.data;
          this.form.photo = res.id;
          console.log('ddddsaa', res);
        })
        .catch((err) => {
          console.log('上传失败', err);
        });
    },

    // 获取人员列表
    handleQuery(val) {
      this.loading = true;
      let params = {
        type: '9cfc06e1-8285-4c05-81e6-69a33b0d8e38',
        page: val ? '' : this.pageRequest.page,
        limit: val ? '' : this.pageRequest.limit,
        auditStatus: 1
      };
      let param = Object.assign(params, { ...this.filters });
      this.$api.personnel
        .queryList(param)
        .then((res) => {
          if (res.code == 0) {
            this.loading = false;
            this.visitantList = res.data;
            this.totalSize = res.count;
            this.visitantList.forEach((item, index) => {
              //  身份证加密

              item.names = this.formatName(item.name);
              item.photoCheck = index + 1;
              if (item.HID) {
                item.HID = item.houser[0].HID;
              }
              this.registOption.map((its) => {
                if (item.registration == its.DID) {
                  item.regist = its.name;
                }
              });
              this.villageList.map((val) => {
                if (item.CID == val.CID) {
                  item.CIDD = val.name;
                }
              });
            });
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$message({
            type: 'error',
            message: '获取列表失败' + res.msg
          });
        });
    },
    // 家庭成员
    async parentHandleclick(row) {
      if (row[0].HID) {
        this.familyArr = [];
        this.loading = true;
        let res = await this.$api.home.sys_family_list({
          page: 1,
          limit: 20,
          auditStatus: 1,
          HID: row[0].HID
        });
        this.loading = false;
        if (res.code !== 0) return;
        this.familyArr = res.data;
        this.handltime(row[0]);
      }
    },
    //获取访问时间
    async handltime(item, isTime) {
      this.passLoading = true;
      let params = {}
      if (isTime) {
        params = { ...this.passFilter }
        if (item && item.length) {
          params.startDate = item[0]
          params.endDate = item[1]
        }
      } else {
        this.selectTime = []
        params = {
          PID: item.PID,
          CID: item.CID
        };
        this.passFilter = params
      }
      let param = JSON.stringify(params);
      let res = await this.$api.personnel.visitor_access_recordLog(param);
      console.log(res)
      this.passLoading = false;
      if (res.code !== 0) return;
      this.timeArr = res.data;
      this.accesstime = this.$format(res.data[0].time);
      this.outtime = this.$format(res.data[1].time);
      this.names = res.data[0].device.Name;
    },
    // 弹窗时间选择变化
    timeChange(time) {
      this.handltime(time, true)
    },
    //查询小区
    getCommunityList() {
      this.villageList = this.$store.state.village.villageList;
    },
    //名字脱敏
    formatName(name) {
      var newStr;
      if (name.length === 2) {
        newStr = name.substr(0, 1) + '*';
      } else if (name.length > 2) {
        var char = '';
        for (var i = 0, len = name.length - 2; i < len; i++) {
          char += '*';
        }
        newStr = name.substr(0, 1) + char + name.substr(-1, 1);
      } else {
        newStr = name;
      }
      return newStr;
    },
    // 删除
    handleClear(val) {
      console.log('kkkk', val);
    },
    // 查看详情
    viewDetails() { },
    // 设置时间
    signSubmit() { },
    // 分页
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
